package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.YuvImage;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.Conver_MD5;
import com.nikmesoft.android.referendumfriend.models.ItemHobies;
import com.nikmesoft.android.referendumfriend.models.ItemMyActivities;
import com.nikmesoft.android.referendumfriend.models.MyActivities;
import com.nikmesoft.android.referendumfriend.models.MyGroupImage;
import com.nikmesoft.android.referendumfriend.models.user_login;
import com.nikmesoft.android.referendumfriend.models.userhobies;
import com.nikmesoft.android.referendumfriend.service.ImageDownloader;
import com.nikmesoft.android.referendumfriend.service.LoginHandler;
import com.nikmesoft.android.referendumfriend.service.MyActivitiesHandler;
import com.nikmesoft.android.referendumfriend.service.MyHobbiesHandler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Home extends BaseActivity {
	public static int test = 0;
	private ProgressDialog dialog;
	private WSLoader loader;
	private WSLoader_MyActivities loader2;
	userhobies user = new userhobies();
	MyActivities myactivities=new MyActivities();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
	}

	public void callActivity(View v) {

		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		if (loader2 == null || loader2.isCancelled()
				|| loader2.getStatus() == Status.FINISHED) {
			loader2 = new WSLoader_MyActivities();
			loader2.execute("1","1");
		}
		
	}

	public void call_Activities()
	{
		Intent intent = new Intent(this, Activity1.class);
		Bundle bun=new Bundle();
		bun.putSerializable("myacty",myactivities);
		intent.putExtras(bun);
		startActivity(intent);
	}
	public void callMyGroup(View v) {

		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			loader.execute(String.valueOf((LoginHandler.result.getId())));
		}

	}

	public void callActivityGroup() {

		Intent intent = new Intent(this, Group.class);
		Bundle bun = new Bundle();
		bun.putSerializable("user", user);
		intent.putExtras(bun);
		startActivity(intent);
	}

	public void loadicon() {
		try {
			for (int i = 0; i < user.getArr().size(); i++) {
				Bitmap bm = ImageDownloader
						.downloadImage(user.get(i).getIcon());
				MyGroupImage.ar_bitmap.add(bm);
			}
		} catch (Exception e) {

		}
	}

	private String callWS_MyActivities(String id_user, String page) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<getMyActivities soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<GetMyActivitiesRequest xsi:type=\"rdf:GetMyActivitiesRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"+id_user+"</id_user>"
				+ "<page xsi:type=\"xsd:int\">"+page+"</page>"
				+ "</GetMyActivitiesRequest>"
				+ "</getMyActivities>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}
	private MyActivities xmlParser_MyActivities(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			MyActivitiesHandler handler = new MyActivitiesHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();
		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
	private class WSLoader_MyActivities extends AsyncTask<String, Integer, MyActivities> {

		@Override
		protected MyActivities doInBackground(String... params) {
			MyActivities us = xmlParser_MyActivities(callWS_MyActivities(params[0],params[1]));
			
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(MyActivities result) {
			super.onPostExecute(result);
			dialog.dismiss();
			myactivities=result;
			call_Activities();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
	private String callWS(String name1) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<getMyHobbies soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<GetMyHobbiesRequest xsi:type=\"rdf:GetMyHobbiesRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
				+ "<id_user xsi:type=\"xsd:int\">"
				+ name1
				+ "</id_user>"
				+ "</GetMyHobbiesRequest>"
				+ "</getMyHobbies>"
				+ "</soapenv:Body>" + "</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private userhobies xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			MyHobbiesHandler handler = new MyHobbiesHandler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer, userhobies> {

		@Override
		protected userhobies doInBackground(String... params) {
			userhobies us = xmlParser(callWS(params[0]));
			user = us;
			loadicon();
			return us;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(userhobies result) {
			super.onPostExecute(result);
			callActivityGroup();

			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}

	public void toad(String str) {
		CommonUtil.toastNotify(this, str);
	}

	public void callSetting(View v) {
		Intent intent = new Intent(this, Setting.class);
		startActivity(intent);
	}

	public void callMyprofile(View v) {

		Intent intent = new Intent(this, Profile.class);
		startActivity(intent);
	}

	public void logout(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to exit?");
		builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

				finish();
			}
		});

		builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});

		AlertDialog alert = builder.create();
		alert.show();

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		logout(new View(this));
	}

}
